//! Database resource helpers built on top of the shared resource framework.
pub mod manager;
pub mod router;
pub mod strategy;

pub use manager::DataSourceManager;
pub use router::{ConnectionSource, DataSourceRouter};
pub use strategy::{DataMergeStrategy, MergeResult};

pub use price_common::resource::{
    ResourceCache, ResourceContext, ResourceError as CommonResourceError, ResourceManager, ResourceMetadata, ResourceRegistry,
    ResourceResult as CommonResourceResult, ResourceRouter as GenericResourceRouter,
};

use thiserror::Error;

/// Uniform error type for database resource operations.
#[derive(Error, Debug)]
pub enum RegionalError {
    #[error("数据源未找到: code={0}, key={1}")]
    DataSourceNotFound(String, String),

    #[error("数据库连接失败: {0}")]
    ConnectionFailed(String),

    #[error("查询失败: {0}")]
    QueryFailed(String),

    #[error("数据合并失败: {0}")]
    MergeFailed(String),

    #[error("配置错误: {0}")]
    ConfigError(String),

    #[error("缓存错误: {0}")]
    CacheError(String),
}

impl RegionalError {
    pub fn from_resource_error(
        err: CommonResourceError,
        context: &ResourceContext,
        code: &str,
    ) -> Self {
        match err {
            CommonResourceError::ResourceNotFound(_) => RegionalError::DataSourceNotFound(code.to_string(), context.resource_key(code)),
            CommonResourceError::LoadFailed(msg) => RegionalError::ConnectionFailed(msg),
            CommonResourceError::ConfigError(msg) | CommonResourceError::RegistryError(msg) => RegionalError::ConfigError(msg),
            CommonResourceError::CacheError(msg) => RegionalError::CacheError(msg),
            CommonResourceError::Other(msg) => RegionalError::ConnectionFailed(msg),
        }
    }
}

pub type RegionalResult<T> = Result<T, RegionalError>;
